package handle

import (
	"book-repo/cache"
	"book-repo/model"
	"book-repo/pkg"
	"encoding/json"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	redis_key := "login" + username
	errData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errData >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误3次禁止登录",
		})
		return
	}
	var user model.User
	err := model.DB.Where("username = ?", username).First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户名不存在",
		})
		return
	}
	if user.Password != pkg.Md5(password) {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if errData == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, "3", time.Hour*3)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误3次，封禁登录",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"user": user,
	})
	return
}
func Loginn(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	redis_key := "login" + username
	errData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errData >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误3次禁止登录",
		})

		return
	}
	var user model.User

	err := model.DB.Where("username = ?", username).First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户名不存在",
		})
		return
	}
	if user.Password != pkg.Md5(password) {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if errData == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, "3", time.Hour*3)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误2次，封禁登录",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
	})
	return
}
func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "5"))
	office := (page - 1) * size
	var users []model.User
	redis_key := "list" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Offset(office).Limit(size).Find(&users)
		jsonData, _ := json.Marshal(users)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &users)
	}

	var total int64
	model.DB.Model(&model.User{}).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"user":  users,
		"total": total,
	})
	return

}
func Detail(c *gin.Context) {
	id := c.Query("id")
	var user model.User
	redis_key := "user_detail" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Where("id = ?", id).Find(&user)
		jsonData, _ := json.Marshal(user)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &user)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"user": user,
	})
	return
}
func Del(c *gin.Context) {
	id := c.Query("id")
	var user model.User
	redis_key := "user_del" + id
	jsonData, _ := json.Marshal(&user)
	cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	err := model.DB.Where("id = ?", id).Delete(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "删除失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
	return
}
func UserRoleList(c *gin.Context) {
	uid, _ := strconv.Atoi(c.Query("uid"))
	var user model.Role
	//SELECT
	//  *
	//FROM
	//  roles
	//  LEFT JOIN user_roles ON user_roles.rid = roles.id
	//  WHERE user_roles.uid=1
	model.DB.Table("roles").
		Joins("LEFT JOIN user_roles ON user_roles.rid = roles.id").Where("user_roles.uid = ?", uid).Find(&user)
	c.JSON(200, gin.H{
		"code": 200,
		"user": user,
	})
	return

}
func RoleNodeList(c *gin.Context) {
	rid, _ := strconv.Atoi(c.Query("rid"))
	var user model.Role
	//SELECT
	//  *
	//FROM
	//  nodes
	//  LEFT JOIN role_nodes ON role_nodes.nid = nodes.id
	//  WHERE role_nodes.rid=1
	model.DB.Table("nodes").
		Joins("LEFT JOIN role_nodes ON role_nodes.nid = nodes.id").Where("user_roles.rid = ?", rid).Find(&user)
	c.JSON(200, gin.H{
		"code": 200,
		"user": user,
	})
	return

}
func UserOrderList(c *gin.Context) {
	rid, _ := strconv.Atoi(c.Query("rid"))
	var user model.Node
	//SELECT
	//  *
	//FROM
	//  nodes
	//  LEFT JOIN role_nodes ON role_nodes.nid = nodes.id
	//  WHERE role_nodes.rid=1
	model.DB.Table("nodes").
		Joins("LEFT JOIN role_nodes ON role_nodes.nid = nodes.id").
		Where("role_nodes.rid = ?", rid).Find(&user)
	c.JSON(200, gin.H{
		"code": 200,
		"user": user,
	})
}
func OrderNodeList(c *gin.Context) {
	rid, _ := strconv.Atoi(c.Query("rid"))
	var node model.Node
	//SELECT
	//  *
	//FROM
	//  nodes
	//  LEFT JOIN role_nodes ON role_nodes.nid = nodes.id
	//  WHERE role_nodes.rid = 1
	model.DB.Table("nodes").
		Joins("LEFT JOIN role_nodes ON role_nodes.nid = nodes.id").
		Where("role_nodes.rid", rid).Find(&node)
	c.JSON(200, gin.H{
		"code": 200,
		"node": node,
	})
	return

}
func CarList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "5"))
	office := (page - 1) * size
	var cars []model.CarOrderList
	//SELECT
	//  orders.id AS OrderId,
	//  cars.car_name AS CarName,
	//  cars.car_num AS CarNum,
	//  cars.car_price AS CarPrice,
	//  orders.order_no AS OrderNo,
	//  orders.order_address AS OrderAddress
	//FROM
	//  cars
	//  LEFT JOIN orders ON orders.c_id = cars.id
	redis_key := "car_list" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Table("cars").Select(
			"orders.id AS OrderId",
			"cars.car_name AS CarName",
			"cars.car_num AS CarNum",
			"cars.car_price AS CarPrice",
			"orders.order_no AS OrderNo",
			"orders.order_address AS OrderAddress",
		).Joins("LEFT JOIN orders ON orders.c_id = cars.id").Offset(office).Limit(size).Find(&cars)
		jsonData, _ := json.Marshal(&cars)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &cars)
	}

	var total int64
	model.DB.Model(&model.Order{}).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"cars":  cars,
		"total": total,
	})
	return
}
func CarDetail(c *gin.Context) {
	id := c.Query("id")
	var car model.CarOrderList
	redis_key := "car_Detail" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Table("cars").Select(
			"orders.id AS OrderId",
			"cars.car_name AS CarName",
			"cars.car_num AS CarNum",
			"cars.car_price AS CarPrice",
			"orders.order_no AS OrderNo",
			"orders.order_address AS OrderAddress",
		).Joins("LEFT JOIN orders ON orders.c_id = cars.id").Where("orders.id = ?", id).Find(&car)
		jsonData, _ := json.Marshal(&car)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &car)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"car":  car,
	})
	return

}
